from django.shortcuts import render,get_object_or_404
from django.http import HttpResponse,HttpResponseRedirect
from .models import Question,Choice
from django.urls import reverse
# Create your views here.
def index(request):

    last_question_list = Question.objects.all()
    #last_question_list =[question.question_text \
                    #for question in question_set] 
    #return HttpResponse(str(last_question_list))
    return render(request,'polls/index.html',{'last_question_list':last_question_list})
'''
def detail(request,question_id):
    question = Question.objects.filter(pk = question_id)
    if question:
        return render(request,'polls/detail.html',{'question':question[0]})
    else:
        return HttpResponse('没有这个问题')
'''
def detail(request,question_id):
    try:
        question = Question.objects.get(pk = question_id)

    except Question.DoesNotExist:
        return HttpResponse('没有这个问题')
    
    else:        
        return render(request,'polls/detail.html',{'question':question})
'''
def detail(request,question_id):
    question = get_object_or_404(Question,pk = question_id)
    return render(request,'polls/detail.html',{'question':question})
'''    
def results(request, question_id):
    pass
def vote(request, question_id):
    question = Question.objects.get(pk = question_id)
    #x = request.GET
    try:
        x = request.POST['x']
    except KeyError:
        
        context = {'Error':'请选择一个选项','question':question}
        return render(request,'polls/detail.html',context)
    else:
        choice = Choice.objects.get(id = x)
        choice.votes+=1
        choice.save()

    
        return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))



def results(request,question_id):
    question = Question.objects.get(pk = question_id)
    #question.choice_set.all
    context = {'question':question}
    return render(request,'polls/results.html',context)
def test(request):
    xlist = ['e','d','c','b','a']
    context = {'xxlist':xlist}
    return render(request,'polls/test.html',context)
    














